package com.easy.controller;

import com.easy.bean.User;
import com.easy.bean.Useraddress;
import com.easy.service.IUserAddressService;
import com.easy.util.LayData;
import com.easy.util.Page;
import com.easy.util.SYS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
@RequestMapping("useraddress")
public class UseraddressController {
    @Autowired
    IUserAddressService userAddressService;


    @RequestMapping("list")
    @ResponseBody
    public LayData getList(Page page, String text, HttpSession session){
        User user = (User)session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        List<Useraddress> list=userAddressService.getList(page,text,user.getId());
        int count=userAddressService.getCount(text);
        return new LayData(count,list);
    }
    @RequestMapping("delete")
    @ResponseBody
    public LayData delete(int id){
        int result=userAddressService.delete(id);
        if (result > 0) {
            return LayData.success("地址删除成功");
        } else {
            return LayData.success(500, "地址删除失败");
        }
    }

    @RequestMapping("add")
    @ResponseBody
    public LayData add(HttpSession session,Useraddress useraddress){
        User user=(User)session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        useraddress.setUserid(user.getId());
        return LayData.success(0,"",userAddressService.add(useraddress));

    }

    @RequestMapping("edit")
    @ResponseBody
    public LayData edit(Useraddress useraddress){
        return LayData.success(0,"",userAddressService.edit(useraddress));
    }

    @RequestMapping("getuseraddressbyid")
    @ResponseBody
    public LayData getUseraddressById(int id) {
        Useraddress address = userAddressService.getUseraddressById(id);
        if (address != null) {
            return LayData.success(address);
        } else {
            return LayData.success(404, "未找到该地址");
        }
    }


    @RequestMapping("setdefault")
    @ResponseBody
    public LayData setDefault(int id, int isdefault, HttpSession session) {
        User user = (User)session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        int result;

        if (isdefault == 1) {
            // 设置为默认地址
            result = userAddressService.setDefault(user.getId(), id);
        } else {
            // 取消默认地址
            result = userAddressService.cancelDefault(id);
        }


            return LayData.success("操作成功");
        }


}
